import mongoose, { ClientSession } from "mongoose";

type TransactionCallback = (session: ClientSession) => Promise<void>;

export const runInTransaction = async (callback: TransactionCallback) => {
	const session=await mongoose.connection.startSession()
	session.startTransaction()
	try {
		await callback(session)
		await session.commitTransaction()
	} catch (err) {
		console.log(err)
		await session.abortTransaction();
		throw err
	} finally {
		await session.endSession();
	}
};
